// 认证服务，处理登录、注册和用户状态管理

// 存储键名
const STORAGE_KEYS = {
  USER: 'pubg_guide_user',
  TOKEN: 'pubg_guide_token'
}

// 模拟用户数据库
let mockUsers = JSON.parse(localStorage.getItem('pubg_guide_mock_users') || '[]')

// 保存模拟用户到本地存储
const saveMockUsers = () => {
  localStorage.setItem('pubg_guide_mock_users', JSON.stringify(mockUsers))
}

// 认证服务接口
export const authService = {
  // 检查用户是否已登录
  isLoggedIn() {
    return !!localStorage.getItem(STORAGE_KEYS.TOKEN)
  },

  // 获取当前登录用户信息
  getCurrentUser() {
    const userData = localStorage.getItem(STORAGE_KEYS.USER)
    return userData ? JSON.parse(userData) : null
  },

  // 登录功能
  async login(username, password) {
    // 模拟API延迟
    await new Promise(resolve => setTimeout(resolve, 500))

    // 在模拟用户数据库中查找用户
    const user = mockUsers.find(
      u => u.username === username && u.password === password
    )

    if (!user) {
      throw new Error('用户名或密码错误')
    }

    // 检查会员是否过期
    if (user.isMember && user.memberExpiry) {
      const expiryDate = new Date(user.memberExpiry)
      if (expiryDate < new Date()) {
        user.isMember = false
        user.memberExpiry = null
        saveMockUsers()
      }
    }

    // 生成模拟token
    const token = `mock_token_${Date.now()}`
    
    // 保存用户信息和token到本地存储
    localStorage.setItem(STORAGE_KEYS.USER, JSON.stringify({
      id: user.id,
      username: user.username,
      email: user.email,
      isMember: user.isMember,
      memberExpiry: user.memberExpiry,
      balance: user.balance
    }))
    localStorage.setItem(STORAGE_KEYS.TOKEN, token)

    return {
      user: {
        id: user.id,
        username: user.username,
        email: user.email
      },
      token
    }
  },

  // 注册功能
  async register(username, email, password) {
    // 模拟API延迟
    await new Promise(resolve => setTimeout(resolve, 500))

    // 检查用户名是否已存在
    if (mockUsers.some(u => u.username === username)) {
      throw new Error('用户名已存在')
    }

    // 检查邮箱是否已存在
    if (mockUsers.some(u => u.email === email)) {
      throw new Error('邮箱已被注册')
    }

    // 创建新用户
    const newUser = {
      id: `user_${Date.now()}`,
      username,
      email,
      password,
      createdAt: new Date().toISOString(),
      isMember: false,
      memberExpiry: null,
      balance: 0
    }

    // 添加到模拟用户数据库
    mockUsers.push(newUser)
    saveMockUsers()

    return {
      id: newUser.id,
      username: newUser.username,
      email: newUser.email,
      createdAt: newUser.createdAt
    }
  },

  // 登出功能
  logout() {
    localStorage.removeItem(STORAGE_KEYS.USER)
    localStorage.removeItem(STORAGE_KEYS.TOKEN)
  },

  // 获取用户列表（仅用于演示）
  getUsers() {
    return mockUsers.map(user => ({
      id: user.id,
      username: user.username,
      email: user.email,
      createdAt: user.createdAt,
      isMember: user.isMember,
      memberExpiry: user.memberExpiry,
      balance: user.balance
    }))
  },

  // 获取用户详细信息（包括敏感信息）
  getUserById(userId) {
    return mockUsers.find(user => user.id === userId)
  },

  // 更新用户信息
  updateUser(userId, updates) {
    const userIndex = mockUsers.findIndex(user => user.id === userId)
    if (userIndex === -1) return null
    
    mockUsers[userIndex] = { ...mockUsers[userIndex], ...updates }
    saveMockUsers()
    
    // 如果是当前登录用户，更新本地存储
    const currentUser = this.getCurrentUser()
    if (currentUser && currentUser.id === userId) {
      localStorage.setItem(STORAGE_KEYS.USER, JSON.stringify({
        ...currentUser,
        ...Object.fromEntries(Object.entries(updates).filter(([key]) => 
          ['isMember', 'memberExpiry', 'balance'].includes(key)
        ))
      }))
    }
    
    return mockUsers[userIndex]
  }
}

// 初始化一些模拟用户数据
if (mockUsers.length === 0) {
  mockUsers = [
    {
      id: 'user_1',
      username: 'admin',
      email: 'admin@example.com',
      password: 'admin123',
      createdAt: new Date(Date.now() - 86400000).toISOString(),
      isMember: true,
      memberExpiry: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(),
      balance: 1000
    },
    {
      id: 'user_2',
      username: 'player1',
      email: 'player1@example.com',
      password: 'player123',
      createdAt: new Date(Date.now() - 172800000).toISOString(),
      isMember: false,
      memberExpiry: null,
      balance: 0
    }
  ]
  saveMockUsers()
}